package com.shujia.scala

import scala.io.Source

object Demo23Score {
  def main(args: Array[String]): Unit = {

    /**
      *
      * 统计每个学生的总分
      * 统计每个班级的平均分
      * 统计每个班级总分最高的学生
      *
      */

    val scores = Source.fromFile("java/data/score.txt").getLines().toList

    val kvList = scores.map(line => {
      val split = line.split(",")
      val id = split(0)
      val score = split(2).toInt

      //学号作为key  分数作为value
      (id, score)
    })

    kvList
      .groupBy(kv => kv._1) //通过学号进行分组
      .map(kv => {
        val id = kv._1

        val sumScore = kv._2.map(kv => {
          val score = kv._2
          score
        }).sum //统计总分

        id + "\t" + sumScore
      })
    //.foreach(println)

    val sunScore: List[(String, Int)] = kvList
      .groupBy(_._1)
      .toList
      .map(kv => {
        val re = kv._2.reduce((x, y) => {
          val sId = x._1
          val iter = x._2 + y._2
          (sId, iter)
        })
        re
      })

    //key学号  value  分数
    val sumScoreMap = sunScore.toMap

    val student = Source.fromFile("java/data/students.txt").getLines().toList

    student.map(line => {
      val split = line.split(",")
      val id = split(0)
      val clazz = split(4)

      //通过学号取出学生总分
      val sumS = sumScoreMap.getOrElse(id, 0)

      //班级作为key  学生分数作为value
      (clazz, sumS)
    }).groupBy(kv => kv._1) //按班级进行分组
      //计算平均分
      .map(kv => {
        val clazz = kv._1
        //班级名
        val ss = kv._2
        //一个班级所有学生的总分
        val ssScore = ss.map(i => {
          val sumScore = i._2
          sumScore
        }).sum

        val avgScore = ssScore / ss.length.toDouble //总分除以人数

        (clazz, avgScore)
      })
      //.foreach(println)


    //统计每个班级总分最高的学生

    student.map(line => {
      val split = line.split(",")
      val id = split(0)
      val clazz = split(4)

      //通过学号取出学生总分
      val sumS = sumScoreMap.getOrElse(id, 0)

      //班级作为key  学生分数作为value
      (clazz, sumS,id)
    }).groupBy(kv=>kv._1)//班级分组
      .flatMap(kv=>{
        val stus = kv._2
        //按总分进行安排  取top10
        val top10 = stus.sortBy(i=> -i._2).take(10)

        //返回一个list  结果扁平化
        top10
      })
      .foreach(println)


  }
}
